package com.nondo.rdp.stock.endpoint.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.stock.domain.StockChoose;
import com.nondo.rdp.stock.logic.MarketLogic;
import com.nondo.rdp.stock.model.AsharesBean;
import com.nondo.rdp.stock.model.MarketBean;
import com.nondo.rdp.stock.service.StockChooseService;

/**
 * 股票行情API处理接口
 */
@RestController("apiStockMarket")
@RequestMapping("/api/stock/market")
public class MarketEndpoint {
    @Autowired
    MarketLogic marketLogic;

    @Autowired
    StockChooseService stockChooseService;

    @RequestMapping("/index")
    public View<Map> index(HttpServletRequest request, HttpServletResponse response) {
        View<Map> view = new View<Map>(20000, "获取数据成功");

        //1、获取三个指数
        JSONObject exponentData = marketLogic.three();
        JSONArray exponentDataFileds = exponentData.getJSONArray("fields");
        JSONArray firstData = exponentData.getJSONArray("000001.SS");
        JSONArray secondData = exponentData.getJSONArray("399001.SZ");
        JSONArray thridData = exponentData.getJSONArray("399006.SZ");

        List exponentMap = new ArrayList();
        Map firstMap = new HashMap();
        Map secondMap = new HashMap();
        Map thirdMap = new HashMap();
        for (int i = 0; i < exponentDataFileds.size(); i++) {
            firstMap.put(exponentDataFileds.get(i), firstData.get(i));
            secondMap.put(exponentDataFileds.get(i), secondData.get(i));
            thirdMap.put(exponentDataFileds.get(i), thridData.get(i));
        }
        exponentMap.add(firstMap);
        exponentMap.add(secondMap);
        exponentMap.add(thirdMap);


        //2、涨列表
        List upList = new ArrayList();
        JSONObject upData = marketLogic.upList();
        JSONArray upDataFilds = upData.getJSONArray("fields");
        for (Map.Entry<String, Object> upItem : upData.entrySet()) {
            if (!upItem.getKey().equals("fields")) {
                Map itemMap = new HashMap();
                JSONArray upItemValue = (JSONArray) JSON.toJSON(upItem.getValue());
                for (int i = 0; i < upDataFilds.size(); i++) {
                    itemMap.put(upDataFilds.get(i), upItemValue.get(i));
                }
                //添加股票代码
                itemMap.put("code", upItem.getKey());
                upList.add(itemMap);
                //倒序排序
                Collections.sort(upList, new Comparator<Map>() {
                    public int compare(Map arg0, Map arg1) {
                        return Float.valueOf(arg1.get("px_change_rate").toString()).compareTo(Float.valueOf(arg0.get("px_change_rate").toString()));
                    }
                });
            }
        }
        //3、跌列表
        List downList = new ArrayList();
        JSONObject downData = marketLogic.downList();
        JSONArray downDataFilds = downData.getJSONArray("fields");
        for (Map.Entry<String, Object> downItem : downData.entrySet()) {
            if (!downItem.getKey().equals("fields")) {
                Map itemMap = new HashMap();
                JSONArray downItemValue = (JSONArray) JSON.toJSON(downItem.getValue());
                for (int i = 0; i < downDataFilds.size(); i++) {
                    itemMap.put(downDataFilds.get(i), downItemValue.get(i));
                }
                //添加股票代码
                itemMap.put("code", downItem.getKey());
                downList.add(itemMap);
                //倒序排序
                Collections.sort(downList, new Comparator<Map>() {
                    public int compare(Map arg0, Map arg1) {
                        return Float.valueOf(arg0.get("px_change_rate").toString()).compareTo(Float.valueOf(arg1.get("px_change_rate").toString()));
                    }
                });
            }
        }

        //输出总数据
        Map returnMap = new HashMap();
        returnMap.put("exponent", exponentMap);
        returnMap.put("upList", upList);
        returnMap.put("downList", downList);

        view.setData(returnMap);

        return view;
    }

    @RequestMapping("/list/updown")
    public View upList(HttpServletRequest request, HttpServletResponse response, @RequestBody AsharesBean asharesBean) {
        View view = new View(20000, "获取数据成功");

        List list = new ArrayList();
        JSONObject upData = marketLogic.upDownList(asharesBean.getStartPos(), asharesBean.getSortType());
        JSONArray upDataFilds = upData.getJSONArray("fields");
        for (Map.Entry<String, Object> upItem : upData.entrySet()) {
            if (!upItem.getKey().equals("fields")) {
                Map itemMap = new HashMap();
                JSONArray upItemValue = (JSONArray) JSON.toJSON(upItem.getValue());
                for (int i = 0; i < upDataFilds.size(); i++) {
                    itemMap.put(upDataFilds.get(i), upItemValue.get(i));
                }
                //添加股票代码
                itemMap.put("code", upItem.getKey());
                list.add(itemMap);
                //选择排序
                if (asharesBean.getSortType() == 1) {
                    Collections.sort(list, new Comparator<Map>() {
                        public int compare(Map arg0, Map arg1) {
                            return Float.valueOf(arg1.get("px_change_rate").toString()).compareTo(Float.valueOf(arg0.get("px_change_rate").toString()));
                        }
                    });
                } else {
                    Collections.sort(list, new Comparator<Map>() {
                        public int compare(Map arg0, Map arg1) {
                            return Float.valueOf(arg0.get("px_change_rate").toString()).compareTo(Float.valueOf(arg1.get("px_change_rate").toString()));
                        }
                    });
                }
            }
        }

        view.setData(list);

        return view;
    }

    @RequestMapping(value = "/info", produces = "application/json", consumes = "application/json")
    public View<Map<String, Object>> info(HttpServletRequest request, HttpServletResponse response, @RequestBody MarketBean marketBean) {
        View<Map<String, Object>> view = new View<Map<String, Object>>(20000, "获取数据成功");

        User user = UserUtils.getUser(request, response);

        String prodCode = marketBean.getCode();

        //1、获取基本real数据
        JSONObject realData = marketLogic.getOne(prodCode);
        JSONArray realDataFields = realData.getJSONArray("fields");
        JSONArray realDataList = realData.getJSONArray(prodCode);
        Map<String, Object> realMap = new HashMap<>();
        for (int i = 0; i < realDataFields.size(); i++) {
            realMap.put(realDataFields.get(i) + "", realDataList.get(i));
        }
        //判断股票是否已经加入了自选
        StockChoose isIn = this.stockChooseService.findByUserAndCode(user, prodCode);
        if (isIn == null) {
            realMap.put("choose", 0);
        } else {
            realMap.put("choose", 1);
        }


        //2、获取基本分时图数据
        JSONObject trendData = marketLogic.getTrend(prodCode);

        //3、返回处理后的数据
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("real", realMap);
        returnMap.put("trend", trendData);

        view.setData(returnMap);

        return view;
    }

    @RequestMapping("/real")
    public View<Map> real(HttpServletRequest request, HttpServletResponse response, @RequestBody MarketBean marketBean) {
        View<Map> view = new View<Map>(20000, "获取数据成功");

        String prodCode = marketBean.getCode();

        JSONObject realData = marketLogic.getOne(prodCode);
        JSONArray realDataFields = realData.getJSONArray("fields");
        JSONArray realDataList = realData.getJSONArray(prodCode);
        Map realMap = new HashMap();
        for (int i = 0; i < realDataFields.size(); i++) {
            realMap.put(realDataFields.get(i), realDataList.get(i));
        }

        view.setData(realMap);

        return view;
    }

    @RequestMapping("/trend")
    public View<Map> trend(HttpServletRequest request, HttpServletResponse response, @RequestBody MarketBean marketBean) {
        View<Map> view = new View<Map>(20000, "获取数据成功");

        String prodCode = marketBean.getCode();

        JSONObject trendData = marketLogic.getTrend(prodCode);
        JSONArray trendDataList = trendData.getJSONArray(prodCode);

        //处理数据上的时间
        for (int i = 0; i < trendDataList.size(); i++) {
            JSONArray item = trendDataList.getJSONArray(i);
            String time = item.get(0).toString().substring(8, 10) + "." + item.get(0).toString().substring(10);//201711010930
            item.set(0, time);
        }

        trendData.put("list", trendDataList);
        trendData.put("prodCode", "");

        view.setData(trendData);

        return view;
    }

    @RequestMapping("/kline")
    public View<Map> kline(HttpServletRequest request, HttpServletResponse response, @RequestBody MarketBean marketBean) {
        View<Map> view = new View<Map>(20000, "获取数据成功");

        String prodCode = marketBean.getCode();
        int candlePeriod = marketBean.getCandlePeriod();
        int dataCount = marketBean.getDataCount();
        String adjustPriceType = marketBean.getAdjustPriceType();

        JSONObject klineData = marketLogic.getKline(prodCode, candlePeriod, dataCount, adjustPriceType);
        JSONArray klineDataList = klineData.getJSONArray(prodCode);
        klineData.put("list", klineDataList);
        klineData.put("prodCode", "");

        view.setData(klineData);

        return view;
    }
    
    @RequestMapping("/concept/updown")
    public View<List<Map<String, String>>> conceptList(HttpServletRequest request, HttpServletResponse response, @RequestBody AsharesBean asharesBean) {
        View<List<Map<String, String>>> view = new View<List<Map<String, String>>>(20000, "获取数据成功");

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        JSONArray updownDatas = marketLogic.upDownConceptList(asharesBean.getStartPos(), asharesBean.getSortType());
        for(int i=0; i<updownDatas.size(); i++){
        	String updownData = String.valueOf(updownDatas.get(i));
        	String[] detailDatas = updownData.split(",");
        	Map<String, String> itemMap = new HashMap<String, String>();
        	itemMap.put("concept_name", detailDatas[2]);
        	itemMap.put("concept_change_rate", detailDatas[3]);
        	itemMap.put("led_prod_code", detailDatas[7]);
        	itemMap.put("led_prod_name", detailDatas[9]);
        	itemMap.put("led_prod_change_rate", detailDatas[11]);
        	list.add(itemMap);
        }
        view.setData(list);

        return view;
    }
}
